package com.lottery.ruok.lottrey.fragment;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.LuziRecyclerViewAdapter;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.ChangLongRefrash;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetLuZiResult;
import com.lottery.ruok.lottrey.retrofitModule.response.LuziResponse;
import com.lottery.ruok.lottrey.ui.widget.PickerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static java.util.Collections.reverse;

/**
 * 作者：xuyf
 * <p>
 * 创建日期：2018/8/17$
 * <p>
 * 描述：长龙模式 ->路子
 */
public class LuziFragment extends BaseFragment implements View.OnClickListener {
    private Context mContext;
    private String mOption;
    @BindView(R.id.no_net_viewstub)
    ViewStub noNetViewstub;
    @BindView(R.id.ll_lu_zi_top)
    LinearLayout llLuZiTop;

    /**
     * 数据有多球的多组数据 -> map1 和单组数据 ->map 分两个map装
     */
    LinkedHashMap<String, List<String>> map = new LinkedHashMap<>();
    LinkedHashMap<String, List<List<String>>> map1 = new LinkedHashMap<>();
    private View mView;
    private TextView mOptionTv;
    private RecyclerView mListView;
    private int mOptionCount = 0;
    private int mCurrentSelected = 0;
    private View emptyLayout;
    private String lotteryCode;
    private List<String> options;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChangLongRefrash event) {
        getResult(false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_luzi, null);
        ButterKnife.bind(this, mView);
        mContext = getActivity();
        initView();
        lotteryCode = getActivity().getIntent().getStringExtra("code");
        getResult(true);
        EventBus.getDefault().register(this);
        return mView;
    }

    private void initView() {
        mOptionTv = mView.findViewById(R.id.option_text);
        mOptionTv.setOnClickListener(this);
        mListView = mView.findViewById(R.id.id_listview);
        mListView.setLayoutManager(new LinearLayoutManager(mContext));
        View view = noNetViewstub.inflate();
        emptyLayout = view.findViewById(R.id.no_net_view);
        emptyLayout.setBackgroundResource(R.color.bg_grey);
        emptyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getResult(true);
            }
        });
    }


    public void getResult(final boolean showDialog) {
        RetrofitBase.getRetrofit()
                .create(GetLuZiResult.class)
                .getResult(lotteryCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribe<ResponseBody>(mContext) {
                    @Override
                    protected void _onNext(ResponseBody responseBody) {
                        if (responseBody != null) {
                            try {
                                /**
                                 * 解析数据
                                 */
                                String json = responseBody.string();
                                JSONObject job = new JSONObject(json);
                                JSONObject data1 = job.getJSONObject("data");
                                String  isData=data1.getString("is_list");
                                if (isData.equals("1")) {
                                    llLuZiTop.setVisibility(View.VISIBLE);
                                    noNetViewstub.setVisibility(View.GONE);
                                    JSONObject list = data1.getJSONObject("list");
                                    JSONObject dic = data1.getJSONObject("dic");
                                    JSONArray sort = data1.getJSONArray("sort");
                                    for (int i = 0; i < sort.length(); i++) {
                                        String key = sort.getString(i);
                                        JSONArray jsonArray = list.getJSONArray(key);
                                        ArrayList<List<String>> lists = new ArrayList<>();
                                        for (int x = 0; x < jsonArray.length(); x++) {
                                            /**
                                             * 对单list json 和多 list 集合进行判断，然后分别进行添加
                                             */
                                            if (jsonArray.get(x) instanceof JSONArray) {
                                                List<String> data = new ArrayList<>();
                                                for (int j = 0; j < jsonArray.getJSONArray(x).length(); j++) {
                                                    data.add(jsonArray.getJSONArray(x).getString(j));
                                                }
                                                lists.add(data);
                                                map1.put(dic.getString(key), lists);
                                            } else {
                                                List<String> data = new ArrayList<>();
                                                for (int j = 0; j < jsonArray.length(); j++) {
                                                    data.add(jsonArray.getString(j));
                                                }
                                                map.put(dic.getString(key), data);
                                            }
                                        }
                                    }
                                    setData();//data 都分别添加完毕后进行数据分拣，然后给ui赋值
                                }else {
                                    llLuZiTop.setVisibility(View.GONE);
                                    noNetViewstub.setVisibility(View.VISIBLE);
                                }

                            } catch (IOException e) {
                                llLuZiTop.setVisibility(View.GONE);
                                noNetViewstub.setVisibility(View.VISIBLE);
                                e.printStackTrace();
                            } catch (JSONException e) {
                                llLuZiTop.setVisibility(View.GONE);
                                noNetViewstub.setVisibility(View.VISIBLE);
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return showDialog;
                    }
                });

    }

    private void setData() {
        mListView.setAdapter(new LuziRecyclerViewAdapter(mContext, getData(0)));
        options = getmOption();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.option_text:
                if (options != null && options.size() > 0) {
                    showPopupWindow(options);
                }
                break;
        }
    }

    /**
     * @param datas 弹出一个球数选择器
     */
    private void showPopupWindow(final List<String> datas) {
        View inflate = getLayoutInflater().inflate(R.layout.popupwindow, null);
        TextView cancle = inflate.findViewById(R.id.cancle);
        TextView comfirm = inflate.findViewById(R.id.comfirm);
        PickerView pickerView = inflate.findViewById(R.id.pickerView);
        pickerView.setData(datas, mCurrentSelected);
        final PopupWindow popupWindow = new PopupWindow(getActivity());
        popupWindow.setContentView(inflate);
        popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        //让pop可以点击外面消失掉
        popupWindow.setOutsideTouchable(true);


        popupWindow.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);//底部弹出

        pickerView.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                mOption = text; //回调选择的内容，

            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });

        comfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOptionTv.setText(mOption);
                mCurrentSelected = datas.indexOf(mOption);
                //根据选择的球数更新ui
                mListView.setAdapter(new LuziRecyclerViewAdapter(mContext, getData(mCurrentSelected)));
                popupWindow.dismiss();
            }
        });


    }

    /**
     * @return List<String>
     * 根据后台返回的多组数据设置相对应的球数选择器
     */
    public List<String> getmOption() {
        List<String> option = new ArrayList<String>();
        Resources resources = getResources();
        String[] stringArray = resources.getStringArray(R.array.options);
        if(Common.isRacing(lotteryCode)){
            option.add("冠军");
            option.add("亚军");
            for (int i = 2; i < mOptionCount; i++) {
                option.add("第" + stringArray[i] + "名");
            }
        }else{
            for (int i = 0; i < mOptionCount; i++) {
                option.add("第" + stringArray[i] + "球");
            }
        }
        if(mOptionCount>0){
            mOption = option.get(0);
            mOptionTv.setText(mOption);
        }
        return option;
    }

    public List<LuziResponse> getData(int option) {
        List<LuziResponse> luziResponses = new ArrayList<>();
        /**
         * 单组数据进行排序并转换成List集合
         */
        ListIterator<Map.Entry<String, List<String>>> reverseMap = new ArrayList<>(map.entrySet()).listIterator(map.size());
        while (reverseMap.hasPrevious()) {
            Map.Entry<String, List<String>> previous = reverseMap.previous();
            LuziResponse luziResponse = new LuziResponse();
            luziResponse.setGameName(previous.getKey());
            luziResponse.setData(previous.getValue());
            luziResponses.add(luziResponse);
        }
        /**
         * 多组数据进行排序并转换成List集合，第一次加载选在第一条数据
         */
        ListIterator<Map.Entry<String, List<List<String>>>> reverseMap1 = new ArrayList<>(map1.entrySet()).listIterator(map1.size());
        while (reverseMap1.hasPrevious()) {
            Map.Entry<String, List<List<String>>> previous = reverseMap1.previous();
            if (previous.getValue().size() > option) {
                LuziResponse luziResponse = new LuziResponse();
                luziResponse.setGameName(previous.getKey());
                luziResponse.setData(previous.getValue().get(option));
                mOptionCount = previous.getValue().size();
                luziResponses.add(luziResponse);
            }
        }
        reverse(luziResponses);
        return luziResponses;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
